var json = {};
$(function() {
	var service = new EbeimService();
	var user = plugin.cookieToJson(document.cookie);
	var jusername = $("#j-username"), jrole = $("#j-role");
	jusername.html(user.username);
	if (user.role == "SYSADMIN") {
		jrole.html("系统管理员");
	} else if (user.role == "ADMIN") {
		jrole.html("管理员");
	} else {
		jrole.html("普通用户");
	}
	json.isMac = 0;
	service.getMonitorDatasource(json, callback1);
});
function macSelect() {
	var service = new EbeimService();
	var checkbox = document.getElementById('teminal');
	if (checkbox.checked) {
		json.isMac = 1;
	} else {
		json.isMac = 0;
	}
	service.getMonitorDatasource(json, callback1);
}

function callback1(data) {
	var allspace = parseInt(data.userSpace);
	var useSpace = data.safeBox.space_usage;
	$("#useSpace").text(fileSizeTransfer(useSpace));
	$("#space").text(fileSizeTransferNoPoint(allspace));
	$("#spaceRate").text((useSpace / allspace * 100).toFixed(2) + "%");
	var list = data.list;
	var liststr = "";
	for (i = 0; i < list.length; i++) {
		liststr += common(list[i], allspace, data.mac);
	}
	$("div#dataContent").html(liststr);
	backuptimetick();
}
function backuptimetick() {
	var dslist = $("em[name='backuptime']");
	for (var j = 0; j < dslist.length; j++) {
		var obj = dslist[j];
		if (obj.attributes.length == 3) {
			if (obj.innerHTML != "等待备份") {
				var str = betwDaysStr(parseInt(obj.attributes[1].value));
				obj.innerHTML = str;
			}
		} else {
			var str = hasBackupTime(parseInt(obj.attributes[1].value));
			obj.innerHTML = str;
		//	obj.innerHTML = Math.floor((new Date().getTime()-parseInt(obj.attributes[1].value))/1000);
		}
	}
	window.setTimeout("backuptimetick()", 1000);
}

function common(ds, allspace, mac) {
	var name = ds.name;
	if (name.length > 14) {
		name = name.substr(0, 14) + "...";
	}
	var usedSpace = fileSizeTransfer(ds.space_usage);
	/* var space = (usedSpace / 1024 / 1024 / 1024).toFixed(1)); */
	var rate = (ds.space_usage / allspace * 100).toFixed(2);
	allspace = fileSizeTransferNoPoint(allspace);
	var str = "";
	str += '<div class="now-group">';
	str += '<div class="item clearfix">';
	str += '  <div class="item-ico ico-file fl"></div>';
	str += '  <div class="item-name fl"> <p class="style-two" title="'
			+ ds.name + '">' + name + '</p><p > ' + ds.bind_device_name
			+ '</p></div>';
	str += ' <div class="item-size fl">' + usedSpace + '</div>';
	str += ' <div class="item-percent fl"><p>节点空间大小：' + allspace
			+ '</p> <p>空间使用率：' + rate + '%</p></div>';
	if (ds.ds_status == 0) {
		str += ' <div class="item-state fl"><p class="style-one normal">正常</p> </div>';
		str += '</div>' 
		str += '<div class="item-route" title="'+ds.root+'">';
		str += '路径：'+ds.root;
		str += '</div>'
		str	+= getStatusStr(ds, mac);

	} else {
		str += ' <div class="item-state fl"> <p class="style-one stop">停用</p> </div>';
		str += '</div>' 
		str += '<div class="item-route" title="'+ds.root+'">';
		str += '路径：'+ds.root;
		str += '</div>'
		str += '</div>';
	}
	str += '</div>';
	return str;
}
function getSenceds(ns) {
	var date = new Date().getTime();
	var second = (date - ns) / 1000;
	return parseInt(second);
}
function changeTitle(dsId,isSelf) {
	document.title = '文件弹窗|/web/html/client-list.html?dsType=0&isSelf='+isSelf+'&dsId=' + dsId;
	document.title = '大窗口|/web/html/safebox.html';
}
function getStatusStr(ds, mac) {
	var stastr = "";
	var isSelf=1;
	if(ds.terminal_id!=mac)
	{
		isSelf=0;
	}
	// 状态为1：备份中..
	if (ds.status == 1) {
		var redirect = "window.open('/web/html/client-list.html?dsType=0','_blank')";
		stastr += '<div class="opera clearfix" >';
		stastr += ' <div class="tips fl">';
		stastr += ' <span class="state">数据源正在执行备份...</span>';
		stastr += '  <span class="time">已执行 <em  name="backuptime" data-dstime="'+ds.begin_time+'" >'
				+ getSenceds(ds.begin_time) +'</em></span>';
		stastr += ' </div>';
		stastr += ' <div class="btns fr" name="backupnow">  <a class="btn"  href="/web/html/client-list.html?isSelf='+isSelf+'&dsType=0&dsId='
				+ ds.id
				+ '"  onclick="changeTitle(\''
				+ encodeURI(encodeURI(ds.id))
				+ '\','+isSelf+');return false;">查看执行情况</a></div>';
		stastr += '</div>';
	} else {
		stastr += '<div class="opera clearfix" id="' + ds.id + '">';
		stastr += ' <div class="tips fl">';
		stastr += ' <span class="state">下次备份时间：' + getTime(ds.next_run)
				+ '</span>';
		stastr += ' <span class="time">' + betwDays(ds.next_run) + '</span>';
		stastr += ' </div>';
		if (ds.terminal_id == mac) {
			// if (ds.status == 0) {
			// stastr += ' <div class="btns fr" name="backupwait" data-id="'
			// + ds.id
			// + '"> <button class="btn" type="button">等待备份</button> </div>';
			// } else {
			var onclick = "javascript:handBackup('" + ds.id + "','"
					+ ds.ds_security_rank + "')";
			stastr += ' <div class="btns fr" name="backupready" data-id="'
					+ ds.id
					+ '">  <button class="btn" type="button" onclick ="'
					+ onclick + '">立即执行</button> </div>';
			// }
		}
		stastr += '</div>';
	}
	return stastr;
}
var $dsId;
function setDynamicCode() {
	var dynamicCode = $("#dynamicCode").val().replace(/(^\s+)|(\s+$)/g,"");
	if (dynamicCode == "") {
		plugin.msgtip({
			type : "e",
			msg : "动态验证码不能为空!"
		});
		return;
	}
	var h_whichGetModel = $("#h_whichGetModel").val();
	if (h_whichGetModel == "handBackup") {
		var dsSecurityRank = $("#h_dsSecurityRank").val();
		handBackup($dsId, dsSecurityRank, dynamicCode);
	} else {
		var version = $("#h_version").val();
		recovery(version, dynamicCode);
	}
}

function handBackup(dsId, dsSecurityRank, dynamicCode) {
	$dsId = dsId;
	var service = new EbeimService();
	$("#h_whichGetModel").val("handBackup");
	$("#h_dsId").val(dsId);
	$("#h_dsSecurityRank").val(dsSecurityRank);
	service.backup({
		dsId : dsId,
		dsSecurityRank : dsSecurityRank,
		dynamicCode : dynamicCode
	}, handBackupCB);
}

var handBackupCB = function(data) {
	var json = data;
	if (json.code == "200" || json.code == 200) {
		closeCodeWindow();
		plugin.msgtip({
			type : "o",
			msg : "成功加入备份队列!"
		});
		$("#dynamicCode").val("");
		setTimeout(function() {
			macSelect();
		}, 3000);
	} else {
		dsSecurityRankCheck(json, json.message);
	}
}

function resetInfo() {
	window.location.reload();
}
function getTime(time) {
	var date = new Date(parseInt(time));
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var day = date.getDate();
	var hour = date.getHours();
	var minute = date.getMinutes();
	var second = date.getSeconds();

	return year + "-" + checkTime(month) + "-" + checkTime(day) + " "
			+ checkTime(hour) + ":" + checkTime(minute) + ":"
			+ checkTime(second);
}
function checkTime(time) {
	if (time < 10) {
		time = "0" + time;
	}
	return time;
}
function betwDays(ns) {
	var betwwen = "";
	var today = new Date().getTime();
	var nTime = ns - today;
	if (nTime < 0) {
		return "<em>等待备份</em>";
	} else {
		betwwen += "<em name='backuptime'  data-dstime ='" + ns + "' data-type='1'>"
				+ betwDaysStr(ns) + "</em> ";
	}
	return betwwen;
}

function betwDaysStr(ns) {
	var betwwen = "";
	var today = new Date().getTime();
	var nTime = ns - today;
	if (nTime <= 0) {
		return "等待备份";
	} else {
		// 计算相差的月数
		var leave = nTime % (12 * 30 * 24 * 3600 * 1000);
		var months = Math.floor(leave / (30 * 24 * 3600 * 1000));
		// 计算出相差天数
		var leave0 = leave % (30 * 24 * 3600 * 1000);
		var days = Math.floor(leave0 / (24 * 3600 * 1000));
		// 计算出小时数
		var leave1 = leave0 % (24 * 3600 * 1000); // 计算天数后剩余的毫秒数
		var hours = Math.floor(leave1 / (3600 * 1000));
		// 计算相差分钟数
		var leave2 = leave1 % (3600 * 1000); // 计算小时数后剩余的毫秒数
		var minutes = Math.floor(leave2 / (60 * 1000));
		// 计算相差秒数
		var leave3 = leave2 % (60 * 1000); // 计算分钟数后剩余的毫秒数
		var seconds = Math.round(leave3 / 1000);
		if (months != 0) {
			betwwen = months + "月" + days + "天"+hours + "小时" + minutes + "分" + seconds + "秒后执行";
		} else if (days != 0) {
			betwwen = days + "天"+hours + "小时" + minutes + "分" + seconds + "秒后执行";
		} else if (hours != 0) {
			betwwen = hours + "小时" + minutes + "分" + seconds + "秒后执行";
		} else if (minutes != 0) {
			betwwen = minutes + "分" + seconds + "秒后执行";
		} else if (seconds != 0) {
			betwwen = seconds + "秒后执行";
		}else{
			betwwen = "等待备份";
		}
	}
	return betwwen;
}


function hasBackupTime(ns) {
	var betwwen = "";
	var today = new Date().getTime();
	var nTime = today - ns;
		// 计算相差的月数
		var leave = nTime % (12 * 30 * 24 * 3600 * 1000);
		var months = Math.floor(leave / (30 * 24 * 3600 * 1000));
		// 计算出相差天数
		var leave0 = leave % (30 * 24 * 3600 * 1000);
		var days = Math.floor(leave0 / (24 * 3600 * 1000));
		// 计算出小时数
		var leave1 = leave0 % (24 * 3600 * 1000); // 计算天数后剩余的毫秒数
		var hours = Math.floor(leave1 / (3600 * 1000));
		// 计算相差分钟数
		var leave2 = leave1 % (3600 * 1000); // 计算小时数后剩余的毫秒数
		var minutes = Math.floor(leave2 / (60 * 1000));
		// 计算相差秒数
		var leave3 = leave2 % (60 * 1000); // 计算分钟数后剩余的毫秒数
		var seconds = Math.round(leave3 / 1000);
		if (months != 0) {
			betwwen = months + "月" + days + "天"+hours + "小时" + minutes + "分" + seconds + "秒";
		} else if (days != 0) {
			betwwen = days + "天"+hours + "小时" + minutes + "分" + seconds + "秒";
		} else if (hours != 0) {
			betwwen = hours + "小时" + minutes + "分" + seconds + "秒";
		} else if (minutes != 0) {
			betwwen = minutes + "分" + seconds + "秒";
		} else if (seconds != 0) {
			betwwen = seconds + "秒";
		}else{
			betwwen = "等待备份";
		}
	return betwwen;
}
